<template>
  <el-cascader 
    :change-on-select="isChangeOnSelect" 
    placeholder="请选择医院类型" 
    :options="classifyTree" 
    :props="props" 
    @change="handleItemChange" 
    v-model="classifyValues">
  </el-cascader>
</template>

<script>
import ClassifyRegionApi from '@/api/components/classifyRegion';
  export default{
    props:{
      classifyValues: {
        type: Array,
        default:() => []
      },
      isChangeOnSelect: {
        type: Boolean,
        default: () => false
      }
    },
    data(){
      return {
        classifyTree: [],
        props:{
          value:'classifyId',
          label:'classifyName'
        },
        classifyIds: []
      }
    },
    methods:{
      getRegionTree(){
        ClassifyRegionApi.getInstituClass()
          .then(res => {
            this.classifyTree = res.data;
            this.removeChildren(this.classifyTree);
            if(this.classifyValues && this.classifyValues.length > 0){
              for(let i=0; i<this.classifyValues.length-1; i++){
                this.classifyIds.push(String(this.classifyValues[i]));
              }
            }
          })
      },
      removeChildren(regions){
        for(let i= 0,len = regions.length;i<len;i++){
          if(regions[i].children.length === 0){
            delete regions[i].children;
          }else {
            this.removeChildren(regions[i].children)
          }
        }
      },
      handleItemChange(val){
        console.log('classify---->' + val);
        var cityValue = "";
        var areaValue = "";
        var fourValue = "";
        let name = "";

        let province = this.classifyTree.filter(item => {
          return item.classifyId == val[0]
        });
        name += province[0].classifyName + ",";
        console.log('classify---->' + JSON.stringify(province));
        if(val[1]){
          let city = province[0].children.filter(item => {
            return item.classifyId == val[1];
          })
          cityValue = city[0].classifyName
          name += cityValue + ",";
          if(val[2]){
            let area = city[0].children.filter(item => {
              return item.classifyId == val[2];
            })
            areaValue = area[0].classifyName
            name += areaValue + ",";
            if(val[3]){
              let four = area[0].children.filter(item => {
                return item.classifyId == val[3];
              })
              fourValue = four[0].classifyName
              name += fourValue + ",";
            }
          }

        }
        if (name.length > 1){
          name = name.substring(0,name.length-1);
        }
        this.$emit("classifyRegionChange",{
          classifyId : val,
          classifyName : name
        });
      }
    },
    mounted(){
      this.getRegionTree();
    }
  }
</script>
